<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Boxes</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>

    <script src="../include/utils.js"></script>
    <script src="./classes/box.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          boxes = [],
          activeBox = createBox(),
          gravity = 0.2;

      function createBox () {
        var box = new Box(Math.random() * 40 + 10, Math.random() * 40 + 10);
        box.x = Math.random() * canvas.width;
        boxes.push(box);
        return box;
      }

      function drawBox (box) {
        if (activeBox !== box && utils.intersects(activeBox, box)) {
          activeBox.y = box.y - activeBox.height;
          activeBox = createBox();
        }
        box.draw(context);
      }

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        activeBox.vy += gravity;
        activeBox.y += activeBox.vy;

        if (activeBox.y + activeBox.height > canvas.height) {
          activeBox.y = canvas.height - activeBox.height;
          activeBox = createBox();
        }
        boxes.forEach(drawBox);
      }());
    };
    </script>
  </body>
</html>
